<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Log
 * @subpackage Writer
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Stream.php 8064 2008-02-16 10:58:39Z thomas $
 */

/** Zend_Log_Writer_Abstract */
require_once 'MAIN/Menu/Abstract.php';

/**
 * @category   Mdt
 * @package    Mdt_Writer
 * @subpackage Writer
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Stream.php 8064 2008-02-16 10:58:39Z thomas $
 */
class MAIN_Menu extends MAIN_Menu_Abstract
{

    var $d_Menu = "back";

    public function RenderMenu(&$dataArray,$param) {
        $d_Menu = "front";
        $lang = ($_COOKIE[LANG])?$_COOKIE[LANG]:"TH";
        $section_id="1";
		$generic = System_Controller::getGeneric('mtmenu','master');
        if (!is_array($dataArray)) return;
        $sHTML = "";
        $sHTML .= "var menubar = [ _cmSplit,\n";

        $html = "";
        #_print($dataArray);
		$img_blank = "<img src=\"".IMG_URL."/menu/2_07.png\">";
        foreach ($dataArray as $menuItem) {
        	$menuLavel = $menuItem[section_level];
        	$section_id=$menuItem[section_id];
        	$section_name = unserialize($menuItem[section_name]);
        	$menuItem['section_name']=$section_name[$lang];

        	$section_link=unserialize($menuItem[section_link]);
            $menuItem[section_link] = $section_link[$d_Menu];
            $menuItem['section_link'] = ($menuItem[section_link])?APP_URL.$menuItem[section_link]."/pid/{$menuItem[section_id]}/menu_id/".$menuItem[section_id]:"";
            if(!$menuItem['section_link'])continue;

        	$html .= "['','".$menuItem['section_name']."','".$menuItem['section_link']."',null,'".$menuItem['section_name']."'";

            $parentID = $menuItem[section_id];

            $html .= MAIN_Menu::RenderSubMenu($menuItem,$menuLavel,$section_id,$parentID);
            $html .= "],\n _cmSplit,\n";
        }
        $sHTML .= substr($html,0,-1);
        $sHTML .= "\n];cmDraw ('imenubar', menubar, 'hbr', cmThemeEForm, 'ThemeEForm');";
//        _print($sHTML);
        return "<script>".$sHTML."</script>";
    }

    protected function RenderSubMenu($_menuItem,$_menuLavel,$section_id, &$parentID) {
        $d_Menu = "front";
        $lang = ($_COOKIE[LANG])?$_COOKIE[LANG]:"TH";
        if (!$_menuItem) return;
        $m_MenuItem = MAIN_Menu::_getTreeBranch($_menuItem[section_id],$_menuItem[section_level]+1);
        $_menuLavel = $_menuLavel+1;
        $_html = "";
        if ($_menuItem) {
//_print($m_MenuItem);
		if(!is_array($m_MenuItem))return;
            foreach ($m_MenuItem as $menuItem) {
            	$menuLavel2 = $menuItem[section_level];
            	$_section_id = $menuItem[section_id];
            	$section_name = unserialize($menuItem["section_name"]);
        		$menuItem["section_name"]=$section_name[$lang];

        		$section_link=unserialize($menuItem[section_link]);
            	$menuItem[section_link] = $section_link[$d_Menu];
            	$menuItem['section_link'] = ($menuItem[section_link])?APP_URL.$menuItem[section_link]."/pid/$parentID/menu_id/".$menuItem[section_id]:"";
            	$menu_id = $section_id."_".$_section_id;
            	if($menuLavel2 == $_menuLavel){
	            	$_html .= "\n,['','".$menuItem["section_name"]."','".$menuItem['section_link']."',null,'".$menuItem["section_name"]."'";
	            	$_html .= MAIN_Menu::RenderSubMenu($menuItem,$menuLavel2,$menu_id,$parentID);
	            	$_html .= "],_cmSplit,";
            	}
            }
        }
//        _print($_html);
        return $_html;
    }

    protected function _getTreeBranch($menuID,$menuLV) {
        if(!class_exists("System_Menu"))
                Zend_Loader::loadClass("System_Menu");
            $_menu = null;
            $_menu = System_Menu::factory("Dbtree", array("tablename" => "menu_master_front"));
            System_Menu::setDefaultAdapter($_menu);
        $profile = $this->getProfile();

        $condition = "";
        $config = $_menu->getConfiguration();

        if ( isset($menuID) && !empty($menuID) ) {
            $sql = "SELECT * FROM ". $config["tablename"] ." ".
                   "WHERE ({$config["prefix"]}_id = '$menuID') AND section_status = 'Y' ";
             if(!$profile->member_id)
				$sql.=" AND section_member != 'Y' ";
			#echo $sql;
                   //"AND section_id IN (SELECT m_id FROM lookup_menu WHERE lookup_name ='{$profile->menu_name}') ";
            $adapter = $_menu->getAdapter();
            $recordset = $adapter->db->Execute($sql);

            if(!$recordset) return '';

            if ($item = $recordset->FetchRow()){
                $condition = array(
                    'and' => array(
                        "section_left >= ".(int)$item["{$config["prefix"]}_left"],
                        "section_right <= ". (int)$item["{$config["prefix"]}_right"],
                        "section_status = 'Y' "
                    )
                );
            }
        }
        if(!$profile->member_id)
        	$condition['and'][]=" section_member !='Y' ";

        if(!$condition)return;

        $adapter->Full("*", $condition);
        if ( !empty($adapter->ERRORS_MES) ) {
            require_once "System/Menu/Exception.php";
            throw new System_Menu_Exception($adapter->ERRORS_MES);
        }
        return $adapter->res->toArray();
    }


    public function topMenuFormat(& $dataArray, & $smarty) {
        $d_Menu = "front";
        if (!is_array($dataArray))
            return "";
         $lang = ($_COOKIE[LANG])?$_COOKIE[LANG]:"TH";
        $g_image= $smarty->_tpl_vars['g_image'];
        $html = '<div id="@id" align="left">' . "\n";
		$html .='<table border="0" cellspacing="0" cellpadding="0" class="menuhead" width="100%"><tr>';
        $last= end(array_values($dataArray));
        foreach ($dataArray as $index => $record) {
            $section_name=unserialize($record[section_name]);
            $record[section_name] = $section_name[$lang];
            $section_link=unserialize($record[section_link]);
            $record[section_link] = $section_link[$d_Menu];
            $record['section_link'] = ($record[section_link])?$record['section_link']."/menu_id/".$record['section_id']:"";
            if(!$record['section_link'])continue;
           /* if ($index >= 6) {
                if ($index == 6) {
                    $html .= '<a href="javascript:void(0);" onMouseOver="MM_swapImage(\'Image' . ($index +1) . '\',\'\',\'' . $g_image . '/m_more_on.gif\',1)" onMouseOut="MM_swapImgRestore()" id="designanchor"><img src="' . $g_image . '/m_more.gif" name="Image' . ($index +1) . '" border="0" id="Image' . ($index +1) . '"></a>' . "\n";
                    $html .= '<div id="mymenu1" class="outlinemenu">' .
                             '<ul>';
                }
                $html .= '<li><a href="#" onclick="app.gotoview(\'' . $record['section_link'] . '\');"><img src="' . $g_image . '/' . $record['section_name'] . '.gif" width="15" hight="15" border="0"/>&nbsp;&nbsp;' . ucfirst($record['section_name']) . '</a></li>';
                if ($index == $last) {
                    $html .= '</ul></div>' . "\n";
                }
            }*/
                $_func= $record['section_link'] ? 'app.gotoview(\'' . $record['section_link'] . '\')' : '';
                $html .= '<td><table border="0" cellspacing="0" cellpadding="0"><tr><td><img src="'.IMG_URL.'/menu/2_07.png" /></td>';
                $html .= '<td class="menuhead" width="100%"><a href="javascript:' . $_func . ';" >'.$record['section_name'].'</a></td>' . "\n";
                $html .= '<td><img src="'.IMG_URL.'/menu/2_055.png"/></td></tr></table></td>';
        }
        $html .= '</tr></table>';
        $html .= '</div>' . "\n";
        return $html;
    }

    public function topMenuFormat2(&$dataArray,$param) {
        $d_Menu = "front";
        if(!is_array($dataArray)) return "";
		$link_default = $param[module]."/".$param[controller]."/".$param[action];
		$lang_data =array("1"=>array("code"=>"EN"),"2"=>array("code"=>"TH"));

		foreach($lang_data as $item){
			$text[$item[code]] = "var menubar =[";
			$menu_level[$item[code]]=0;
		}
		//$table = "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr>";
		//$table_end = "</tr></table>";
//		_print($dataArray);
		foreach($dataArray as $menu_id=>$data){
//			if(!$data[section_link]) $data[section_link]="#";

			$section_link=unserialize($data[section_link]);
            $data[section_link] = $section_link[$d_Menu];
            $data[section_link] = ($data[section_link])?$data[section_link]."/menu_id/".$data[section_id]:"#";

			$data[section_name] = unserialize($data[section_name]);
			if($link_default == $data[section_link]){
				$table = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr> " .
						 "<td width=\"9\"><img src=\"".IMG_URL."/menu/2_07.png\" width=\"9\" height=\"30\" /></td> " .
						 "<td background=\"".IMG_URL."/menu/2_08.png\" nowrap><div align=\"center\"><span class=\"style22\">";
				$table_end= "</span></div></td> " .
							"<td width=\"1\"><img src=\"".IMG_URL."/menu/2_055.png\" width=\"9\" height=\"30\" /></td>" .
							"</tr></table>";
			}else{
				$table = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr> " .
						 "<td><img src=\"".IMG_URL."/menu/2_07.png\"/></td>" .
						 "<td background=\"".IMG_URL."/menu/2_08.png\" nowrap><div align=\"center\"><span class=\"style22\">";
				$table_end= "</span></div></td>" .
							"<td><img src=\"".IMG_URL."/menu/2_055.png\"/></td>" .
							"</tr></table>";
			}
			foreach($lang_data as $item){
					$lang = $item[code];
					if($data[section_level]>$menu_level[$lang]){
						if($data[section_level]==1){
							$text[$lang] .="['{$data[$this->table_icon]}','".$table.trim($data[section_name][$lang]).$table_end."','".APP_URL.$data[section_link]."','_self',null,";
						}else{
							$text[$lang] .="['{$data[$this->table_icon]}','".trim($data[section_name][$lang])."','".APP_URL.$data[section_link]."','_self',null,";
						}
					}elseif($data[section_level]==$menu_level[$lang]){
						$len = strlen($text[$lang]);
						$text[$lang] = substr($text[$lang],0,$len-1);
						$text[$lang] .="],";
						if($data[section_level]==1)
							$text[$lang] .="['{$data[$this->table_icon]}','".$table.trim($data[section_name][$lang]).$table_end."','".APP_URL.$data[section_link]."','_self',null,";
						else
							$text[$lang] .="['{$data[$this->table_icon]}','".trim($data[section_name][$lang])."','".APP_URL.$data[section_link]."','_self',null,";
					}elseif($data[section_level]<$menu_level[$lang]){
						$len = strlen($text[$lang]);
						$text[$lang] = substr($text[$lang],0,$len-1);
						$level = ($menu_level[$lang]-$data[section_level])+1;
						for($i=0;$i<$level; $i++)
							$text[$lang] .="],";
						if($data[section_level]==1)
							$text[$lang] .="['{$data[$this->table_icon]}','".$table.trim($data[section_name][$lang]).$table_end."','".APP_URL.$data[section_link]."','_self',null,";
						else
							$text[$lang] .="['{$data[$this->table_icon]}','".trim($data[section_name][$lang])."','".APP_URL.$data[section_link]."','_self',null,";
					}
					$menu_level[$lang] = $data[section_level];
			}
		}

		foreach($lang_data as $item){
			$len = strlen($text[$item[code]]);
			$text[$item[code]] = substr($text[$item[code]],0,$len-1);
			for($i=$menu_level[$item[code]];$i>0; $i--){
					$text[$item[code]] .="],";
			}
			$text[$item[code]] .="];";
			$text[$item[code]] .="\n cmDraw ('imenubar', menubar, 'hbr', cmThemeEForm, 'ThemeEForm');";
		}
		//_print(htmlspecialchars($text[$_COOKIE[LANG]]));die();
		return "<script>".$text[$_COOKIE[LANG]]."</script>";

    }


    public function getHtmlTreeView($params, &$smarty )
  {
    // @todo: acl
    $d_Menu = "back";
//		_print($params);

    $lang = ($_COOKIE[LANG])?$_COOKIE[LANG]:"TH";
    $first = (is_object($smarty) && $smarty instanceof Smarty);
//_print($params["data"]);
       // if ($first) $params["data"] = $params["data"]["children"][0];
        $data = $params["data"];
//        _print($params["data"]);
/*
    if ($first) {
            if($params["data"]["id"]!=1) $params["data"] = $params["data"]["children"][0];
    }

        $data = $params["data"];
*/
    if ( $first )
    {
      Zend_Registry::get("view")->AddJavaScript("treeview");
      if ( $params["id"] ) $attr .= "id=\"{$params["id"]}\" ";
      if ( $params["class"] ) $attr .= "class=\"{$params["class"]}\" ";
    }

        $front    = Zend_Registry :: get("front");
        $base_url = $front->getBaseUrl();
        #$request = $front->getRequest();
        #$http = $request->get("HTTP_REFERER");
        #if(!$http) $http = "http://".$request->get("HTTP_HOST");

    $html = "<ul $attr style=\"display:none;\">"; // class=\"filetree\"

    if ($data["children"])
    {
      while ( list(, $menu) = each($data["children"]) )
      {
                $menu_text = unserialize($menu["text"]);
                $menu[text] = $menu_text[$lang];
                $menu_href = unserialize($menu["href"]);
                $menu[href] = $menu_href[$d_Menu];
                if($menu["href"]){
                  $menu["href"]=$menu["href"]."/menu_id/".$menu["id"];
                  $href = ($menu["href"] && !$menu["children"]) ? "/{$base_url}/{$menu["href"]}" : "/{$base_url}/{$menu["href"]}";//"javascript:void(0);";
                  $href = str_replace("//","/",$href);
        }

                $class = $menu["children"] ? "folder" : "file";
                // if ( $first ) $class = "folder";

        if($href){
          $html .= "<li><span class=\"$class\"><a href=\"{$href}\">{$menu["text"]}</a></span>";
        }else{
          $html .= "<li><span class=\"$class\">{$menu["text"]}</span>";
        }
        if ( $menu["children"] )
          $html .= self::getHtmlTreeView( array("data" => $menu), $tmp = 0);
        $html .= "</li>";
      }
    }
    $html .= "</ul>";

    if ($first)
    {   // class="init-script"
          $html .= "\n".'<script type="text/javascript" charset="utf-8" >' ."\n".
                     '    '."\n".
                   '    $(document).ready(function () {' ."\n".
                     '        $("#'.$params["id"].'").show();'."\n".
                   '        $("#'.$params["id"].'").treeview({persist:"cookie",cookieId: "treeview-'.$params["id"].'"});' ."\n".
                   '    });' ."\n".
                   '</script>';
    }
    return $html;
  }


    public function getHtmlTreeViewFront($params, &$smarty )
  {
    // @todo: acl
    $d_Menu = "front";
//		_print($params);

    $lang = ($_COOKIE["LANG"])?$_COOKIE["LANG"]:"TH";
    $first = (is_object($smarty) && $smarty instanceof Smarty);
//_print($params["data"]);
       // if ($first) $params["data"] = $params["data"]["children"][0];
        $data = $params["data"];
//        _print($params["data"]);
/*
    if ($first) {
            if($params["data"]["id"]!=1) $params["data"] = $params["data"]["children"][0];
    }

        $data = $params["data"];
*/
    if ( $first ) {
        Zend_Registry::get("view")->AddJavaScript("treeview");
        if ( $params["id"] ) $attr .= "id=\"{$params["id"]}\" ";
        if ( $params["class"] ) $attr .= "class=\"".$params["class"]."\"";
    }

    $parentID = $params["parent_id"];

    $front    = Zend_Registry :: get("front");
    $base_url = $front->getBaseUrl();
    $request = $front->getRequest();
	$_params = $request->getParams();

    #$request = $front->getRequest();
    #$http = $request->get("HTTP_REFERER");
    #if(!$http) $http = "http://".$request->get("HTTP_HOST");
    #_print($data);

    $html = "<ul $attr style=\"display:none;\">"; // class=\"filetree\"

    if ($data["children"]) {
        while ( list(, $menu) = each($data["children"]) ) {
            $menu_text = unserialize($menu["section_name"]);
            #_print($menu_text);
            $menu["text"] = $menu_text[$lang];
            $menu_href = unserialize($menu["section_link"]);
            $menu["href"] = $menu_href[$d_Menu];
            if($menu["href"]){
                $menu["href"] = $menu["href"]."/pid/".$parentID."/menu_id/".$menu["section_id"];
                $href = ($menu["href"] && !$menu["children"]) ? "/{$base_url}/{$menu["href"]}" : "/{$base_url}/{$menu["href"]}";//"javascript:void(0);";
                $href = str_replace("//","/",$href);
            }

            $class = $menu["children"] ? "folder" : "file";
            if ( $first ) $class = "folder";
            #$class = "file";

            if($href){
                $html .= "<li><span class=\"$class\"><a href=\"{$href}\">{$menu["text"]}</a></span>";
            } else {
                $html .= "<li><span class=\"$class\">{$menu["text"]}</span>";
            }

            if ($menu["children"]) {
              $html .= self::getHtmlTreeViewFront( array("parent_id"=>$parentID,"data" => $menu), $tmp = 0);
            }

            $html .= "</li>";
        }
    }
    $html .= "</ul>";

    if ($first) {
          // class="init-script"
          $html .= '<script type="text/javascript" language="javascript">' .
                   '$(function(){' .
                   '$("#'.$params["id"].'").show();'.
                   '$("#'.$params["id"].'").treeview({persist:"location"});'.
                   '});' .
                   '</script>';
    }
    return $html;
  }


   /* public function topMenuFormat(&$dataArray, &$smarty) {
        if(!is_array($dataArray)) return "";
        $g_image = $smarty->_tpl_vars['g_image'];
        $html  = '<div id="@id" align="left">'."\n";
        foreach($dataArray as $index=>$record) {
            $_func = $record['section_link']?'app.gotoview(\''.$record['section_link'].'\')':'';
            $html .= '<a href="javascript:'.$_func.';" onMouseOver="MM_swapImage(\'Image'.($index+1).'\',\'\',\''.$g_image.'/m_'.($record['section_name']).'_on.gif\',1)" onMouseOut="MM_swapImgRestore()"><img src="'.$g_image.'/m_'.($record['section_name']).'.gif" name="Image'.($index+1).'" border="0" id="Image'.($index+1).'"></a>'."\n";
        }
        $html .= '</div>'."\n";
        return $html;
    }
    public function topMenuFormat2(&$dataArray) {
        if(!is_array($dataArray)) return "";
    $lang_data =array("1"=>array("code"=>"EN"),"2"=>array("code"=>"TH"));
    foreach($lang_data as $item){
      $text[$item[code]] = "var menubar =[";
      $menu_level[$item[code]]=0;
    }
    $table = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"1\"><tr><td class=\"main_menu\" style=\"cursor:pointer\">";
    $table_end = "</td></tr></table>";
    foreach($dataArray as $menu_id=>$data){
      if(!$data[section_link]) $data[section_link]="#";
      $data[section_name] = unserialize($data[section_name]);

      foreach($lang_data as $item){
          $lang = $item[code];
          if($data[section_level]>$menu_level[$lang]){
            if($data[section_level]==1){
              $text[$lang] .="['{$data[$this->table_icon]}','".$table.trim($data[section_name][$lang]).$table_end."','".APP_URL."$data[section_link]','_self',null,";
            }else{
              $text[$lang] .="['{$data[$this->table_icon]}','".trim($data[section_name][$lang])."','".APP_URL."$data[section_link]','_self',null,";
            }
          }elseif($data[section_level]==$menu_level[$lang]){
            $len = strlen($text[$lang]);
            $text[$lang] = substr($text[$lang],0,$len-1);
            $text[$lang] .="],";
            if($data[section_level]==1)
              $text[$lang] .="['{$data[$this->table_icon]}','".$table.trim($data[section_name][$lang]).$table_end."','".APP_URL."$data[section_link]','_self',null,";
            else
              $text[$lang] .="['{$data[$this->table_icon]}','".trim($data[section_name][$lang])."','".APP_URL."$data[section_link]','_self',null,";
          }elseif($data[section_level]<$menu_level[$lang]){

            $len = strlen($text[$lang]);
            $text[$lang] = substr($text[$lang],0,$len-1);
            $level = ($menu_level[$lang]-$data[section_level])+1;
            for($i=0;$i<$level; $i++)
              $text[$lang] .="],";
            if($data[section_level]==1)
              $text[$lang] .="['{$data[$this->table_icon]}','".$table.trim($data[section_name][$lang]).$table_end."','".APP_URL."$data[section_link]','_self',null,";
            else
              $text[$lang] .="['{$data[$this->table_icon]}','".trim($data[section_name][$lang])."','".APP_URL."$data[section_link]','_self',null,";
          }
          $menu_level[$lang] = $data[section_level];
      }
    }

    foreach($lang_data as $item){
      $len = strlen($text[$item[code]]);
      $text[$item[code]] = substr($text[$item[code]],0,$len-1);
      for($i=$menu_level[$item[code]];$i>0; $i--){
          $text[$item[code]] .="],";
      }
      $text[$item[code]] .="];";
      $text[$item[code]] .="\n cmDraw ('imenubar', menubar, 'hbr', cmThemeOffice, 'ThemeOffice');";
    }
    return "<script>".$text[$_COOKIE[LANG]]."</script>";

    }*/
}